package weeny.pre.face.treetable;



import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.plaf.basic.*;


public class PreGroupTreeTableUI extends BasicTableUI {

	public void paint(Graphics g, JComponent c) {
		Rectangle oldClipBounds = g.getClipBounds();
		Rectangle clipBounds    = new Rectangle(oldClipBounds);
		int tableWidth   = table.getColumnModel().getTotalColumnWidth();
		clipBounds.width = Math.min(clipBounds.width, tableWidth);
		g.setClip(clipBounds);

		int firstIndex = table.rowAtPoint(new Point(0, clipBounds.y));
		int  lastIndex = table.getRowCount()-1;

		Rectangle rowRect = new Rectangle(0,0,
				tableWidth, table.getRowHeight() + table.getRowMargin());
		rowRect.y = firstIndex*rowRect.height;

		for (int index = firstIndex; index <= lastIndex; index++) {
			if (rowRect.intersects(clipBounds)) {
				paintRow(g, index);
			}
			rowRect.y += rowRect.height;
		}
		g.setClip(oldClipBounds);
	}

	private void paintRow(Graphics g, int row) {
		Rectangle rect = g.getClipBounds();
		boolean drawn  = false;

		int numColumns = table.getColumnCount();

		AbstractTreeNode atn = ((PreJTreeTable)table).nodeForRow(row);
		for (int column = 0; column < numColumns; column++) {
			Rectangle cellRect = table.getCellRect(row,column,true);
			int cellRow,cellColumn;
			if (!(atn instanceof FieldNode)) {
				cellRow    = row;
				cellColumn = column;
				if (cellRect.intersects(rect)) {
					drawn = true;
					paintCell(g, cellRect, cellRow, cellColumn);
				} else {
					if (drawn) break;
				} 
			}
			else {
				cellRow = row;
				cellColumn = table.convertColumnIndexToView(0);
				cellRect = table.getCellRect(row,cellColumn,true);
				for (int i = cellColumn; i < numColumns; i++){
					cellRect.add(table.getCellRect(row, i, true));
				}
				if (cellRect.intersects(rect)) {
					drawn = true;
					paintCell(g, cellRect, cellRow, cellColumn);
				} else {
					if (drawn) break;
				}
				break;
			}
		}
	}

	private void paintCell(Graphics g, Rectangle cellRect, int row, int col) {
		int spacingHeight = table.getRowMargin();
		int spacingWidth  = table.getColumnModel().getColumnMargin();

		cellRect.setBounds(
				cellRect.x + spacingWidth/2, cellRect.y + spacingHeight/2,
				cellRect.width - spacingWidth, cellRect.height - spacingHeight);

		if (table.isEditing() && table.getEditingRow()==row &&
				table.getEditingColumn()==col) {
			Component component = table.getEditorComponent();
			component.setBounds(cellRect);
			component.validate();
		}
		else {
			TableCellRenderer renderer = table.getCellRenderer(row, col);
			Component component = table.prepareRenderer(renderer, row, col);

			if (component.getParent() == null) {
				rendererPane.add(component);
			}
			rendererPane.paintComponent(
					g, component, table, cellRect.x, cellRect.y,
					cellRect.width, cellRect.height, true);
		}
	}    
}

